package models

import (
	"github.com/astaxie/beego/orm"
	"math"
)

type Menu struct {
	Id       int    `json:"id"`
	MenuName string `json:"menu_name"`
	MenuUrl  string `json:"menu_url"`
	Pid      int    `json:"pid"`
	Sort     int    `json:"sort"`
	Icon     string `json:"icon"`
	Level    int    `json:"level"`
	Type     int    `json:"type"`
	IsShow   int    `json:"is_show"`
	BaseModels
}

type MenuType struct {
	Id   int
	Name string
}

func NewMenu() *Menu {
	return new(Menu)
}

func MenuTable() string {
	return AdminPrefix + "menu"
}

//获取菜单类型map
func (m *Menu) GetMenuTypeMap() []MenuType {
	var menu = make([]MenuType, 0)
	menu = append(menu, MenuType{1, "导航"})
	menu = append(menu, MenuType{2, "链接"})
	menu = append(menu, MenuType{3, "按钮"})
	return menu
}

func (m *Menu) MenuList() ([]Menu, int64, error) {
	o := orm.NewOrm()
	err := o.Using("blog")
	query := o.QueryTable(new(Menu))
	menu := make([]Menu, 0)
	if m.IsShow != 0 {
		query = query.Filter("is_show", m.IsShow)
	}

	if m.Type == -3 {
		query = query.Exclude("type", math.Abs(float64(m.Type)))
	}

	total, err := query.OrderBy("pid", "-sort").All(&menu)
	return menu, total, err
}

func (m *Menu) FindName(menuUrl string) (*Menu, error) {
	o := orm.NewOrm()
	//_ = o.Using("blog")
	menu := NewMenu()
	err := o.QueryTable(new(Menu)).Filter("menu_url", menuUrl).One(menu)
	if err != nil {
		return menu, err
	}
	return menu, nil
}

func (m *Menu) NavMenuTotal() (int64, error) {
	o := orm.NewOrm()
	_ = o.Using("blog")
	return o.QueryTable(new(Menu)).Filter("level", 1).Count()
}
